# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import serial
import time
import csv
import struct
import requests
import json

url = "http://192.168.195.1:7550/api/fog"
headers = {
  'Content-Type': 'application/json'
}

ser = serial.Serial("/dev/USB0", 9600, timeout=0.01)  # receive data once every 0.1S 
ser.flushInput()

data = ""

V = 0.0 # A0电压值（损失了低2位精度）

pmm = 0.0


f = "./lucky.csv"
line = 0
connect_flag = 1
recover_flag = 0
feedback = struct.pack("BBB",0xaa,0x55,0x01)
    # 怎么把数据存起来？
print("You can always receive data, press Ctrl + C to exit")
with open(f,"w+") as csvfile: 
    while 1: 
        if line>=125:
            line = 0
            csvfile.seek(0,0)  
        while ser.inWaiting() > 0:
            data = ser.readline()# 因为烟雾传感器传输过来的数据长度为4，所以每次只取四个字节的数据
            if data != "":
                if data[0]==170 and data[1]==85:
                    ser.write(feedback)
                    print(data[2])
                    if data[2]==0:
                    # 收到一次烟雾的值就给一个反馈：aa 55 1
                        ser.flush()
                        V = 5.0*(data[3]*4.0)/1024.0  #实际的电压值
                        pmm = pow(11.5428 * 35.904 * V/(25.5-5.1* V),0.6549) #换算后的浓度值 
                     #写入csv文件中
                        csvfile.write(str(pmm) + "\n")
                        print(csvfile.tell())
                        print(pmm)

                        line += 1
                    # # else:#收到历史数据
                    if data[2]==1:
                        fog = []
                        for i in range(3,len(data),4):
                            V = 5.0*(data[i]*4.0)/1024.0  #实际的电压值
                            pmm = pow(11.5428 * 35.904 * V/(25.5-5.1* V),0.6549) #换算后的浓度值 
                            fog.append({"fog": str(pmm)})
                        payload = json.dumps({"value": fog})
                        response = requests.request("POST", url, headers=headers, data=payload)      
                        print(fog)                      
                        print(response.text)
                        print(response.status_code)
                       
                            

                    # if connect_flag == 1 :  # 连接上的
                    #     # 上传数据
                    
                    # if recover_flag == 1:    # 重连
                    #     # 10分钟数据
                    
